<script setup lang="ts">
import { ref } from 'vue';
import { API_CONFIG } from '../../config/apiConfig';
import { ToastService } from '../../utils/toastService';

const props = defineProps<{
  userId: string;
  currentRole?: string;
}>();

const emit = defineEmits<{
  close: [];
  'role-updated': [];
}>();

const roles = [
  { id: 2, name: '管理员' },
  { id: 3, name: '普通用户' },
  { id: 5, name: '毕业学员' },
];

const selectedRole = ref(roles[0].id);

async function handleSubmit() {
  try {
    const response = await fetch(`${API_CONFIG.BASE_URL}/user/role/${props.userId}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify({
        userId: props.userId,
        roleId: selectedRole.value
      })
    });

    const result = await response.json();
    
    if (result.code === "0") {
      ToastService.success('权限修改成功');
      emit('role-updated');
      emit('close');
    } else {
      ToastService.error(`修改失败: ${result.msg}`);
    }
  } catch (error) {
    console.error('修改权限失败:', error);
    ToastService.error('修改权限失败，请检查网络连接');
  }
}
</script>

<template>
  <div class="set-role-form">
    <h2>修改用户权限</h2>
    <form @submit.prevent="handleSubmit">
      <div class="form-group">
        <label>选择权限</label>
        <select v-model="selectedRole" class="role-select">
          <option v-for="role in roles" :key="role.id" :value="role.id">
            {{ role.name }}
          </option>
        </select>
      </div>
      <div class="form-actions">
        <button type="button" class="cancel-btn" @click="emit('close')">取消</button>
        <button type="submit" class="submit-btn">确认</button>
      </div>
    </form>
  </div>
</template>

<style scoped>
.set-role-form {
  padding: 20px;
}

h2 {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #374151;
}

.role-select {
  width: 100%;
  padding: 8px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  font-size: 14px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.cancel-btn,
.submit-btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #f3f4f6;
  border: 1px solid #e5e7eb;
  color: #374151;
}

.submit-btn {
  background-color: #3b82f6;
  border: none;
  color: white;
}

.cancel-btn:hover {
  background-color: #e5e7eb;
}

.submit-btn:hover {
  background-color: #2563eb;
}
</style>